# coding=utf-8

from common.level_strategy.model import MchUser, UserLevelStrategy, UserLevel
from common.utils import track_logging
from common.utils.db import list_object, get, upsert, delete
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)


@sql_wrapper
def get_mch_user(id):
    return get(MchUser, id)


@sql_wrapper
def upsert_mch_user(info, id=None):
    mch_user = MchUser.query.filter(MchUser.mch_id == info['mch_id']).filter(
        MchUser.user_id == info['user_id']).first()
    id = mch_user.id if mch_user else None
    return upsert(MchUser, info, id)


@sql_wrapper
def list_mch_user(query_dct):
    return list_object(query_dct, MchUser)


@sql_wrapper
def delete_mch_user(id):
    delete(MchUser, id)


@sql_wrapper
def get_user_level_strategy(id):
    return get(UserLevelStrategy, id)


@sql_wrapper
def upsert_user_level_strategy(info, id=None):
    return upsert(UserLevelStrategy, info, id)


@sql_wrapper
def list_user_level_strategy(query_dct):
    return list_object(query_dct, UserLevelStrategy)


@sql_wrapper
def delete_user_level_strategy(id):
    delete(UserLevelStrategy, id)


@sql_wrapper
def get_user_level_strategy_by_mch_id(mch_id):
    item = UserLevelStrategy.query.filter(UserLevelStrategy.mch_id == mch_id).first()
    if item is None:
        return 0
    else:
        return item.id


@sql_wrapper
def get_vaild_user_level_strategy_by_mch_id(mch_id):
    return UserLevelStrategy.query.filter(UserLevelStrategy.mch_id == mch_id).filter(
        UserLevelStrategy.status == 1).first()


@sql_wrapper
def get_user_level(id):
    return get(UserLevel, id)


@sql_wrapper
def upsert_user_level(info, id=None):
    return upsert(UserLevel, info, id)


@sql_wrapper
def list_user_level(query_dct):
    return list_object(query_dct, UserLevel)


@sql_wrapper
def delete_user_level(id):
    delete(UserLevel, id)


@sql_wrapper
def get_mch_user_channel_level(mch_id, user_id):
    mch_user = MchUser.query.filter(MchUser.mch_id == int(mch_id)).filter(
        MchUser.user_id == int(user_id)).first()
    if mch_user is None:
        return None
    if mch_user.level is None:
        return None
    user_level = mch_user.level
    level_strategy = get_vaild_user_level_strategy_by_mch_id(int(mch_id))
    if level_strategy is None:
        return None
    level_strategy_id = level_strategy.id
    ul = UserLevel.query.filter(UserLevel.strategy_id == int(level_strategy_id)).filter(
        UserLevel.level == int(user_level)).first()
    if ul is None:
        return None
    return ul.channel_level


@sql_wrapper
def get_mch_user_status(mch_id, user_id):
    if not mch_id or not user_id:
        return True
    mch_user = MchUser.query.filter(MchUser.mch_id == mch_id).filter(
        MchUser.user_id == user_id).first()
    if mch_user is None or mch_user.charge_status is None:
        return True
    return mch_user.charge_status
